package com.l.web.action.system;

import org.apache.log4j.Logger;
import org.l.qiao.Template;
import org.l.qiao.dao.TemplateDAOAbstract;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class TemplateService {

    /**
     *
     */
    private static final long serialVersionUID = -8295243757221772937L;

    private static final Logger LOGGER = Logger.getLogger(TemplateService.class);
    private HttpServletResponse res;
    private TemplateDAOAbstract templatedao;
//    private TemplateCheck check = new TemplateCheck();
    private int pagenumber = 1;
    private int pagecount = 20;
    private Map<String, Object> rslist = null;
    private String updateName = "";
    private String updateValue = "";
    private Template template;

    private String id = "";
    private File upfile;
    private String upfileFileName;
    private String upfileContentType;
    private String path = Template.BASEDIR;
    private String description = "";

    private File downloadfile;
    private String downloadfilename = "";

    public void setTemplatedao(TemplateDAOAbstract templatedao) {
        this.templatedao = templatedao;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setUpfile(File upfile) {
        this.upfile = upfile;
    }

    public void setUpfileFileName(String upfileFileName) {
        this.upfileFileName = upfileFileName;
    }

    public void setUpfileContentType(String upfileContentType) {
        this.upfileContentType = upfileContentType;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setPagenumber(int pagenumber) {
        this.pagenumber = pagenumber;
    }

    public void setPagecount(int pagecount) {
        this.pagecount = pagecount;
    }

    public void setUpdatename(String updateName) {
        this.updateName = updateName;
    }

    public void setUpdatevalue(String updateValue) {
        this.updateValue = updateValue;
    }

    public void upload() throws IOException {
//        JSONObject json = new JSONObject();
//        if (true){//check.checkDescription(description)) {
//
//            Date date = new Date();
//            //File file = new File(ServletActionContext.getServletContext().getRealPath("/") + path);
//            File file = new File("");//ServletActionContext.getServletContext().getRealPath("/") + path);
//            if (!file.exists()) {
//                file.mkdirs();
//            }
//            File savefile = new File(file.toString() + "/" + TimeFile(date));
//            if (upfile.renameTo(savefile)) {
//                Template template = new Template();
//                String id = template.setId();
//                template.put(template.Description, description);
//                template.put(template.Created, date);
//                template.put(template.Path, path + TimeFile(date));
//                templatedao.insert(template);
//                json.put("code", 1);
//                json.put("msg", "文件上传成功!");
//                json.put("id", id);
//            } else {
//                json.put("code", 0);
//                json.put("msg", "文件保存失败!");
//            }
//            res.getWriter().write(" " + json.toString());
//        } else if (true){//check.checkId(id)) {
//            template = new Template(templatedao.findById(id));
//            //File oldfile = new File(ServletActionContext.getServletContext().getRealPath("/") + template.getString(template.Path, ""));
//            File oldfile = new File("");//ServletActionContext.getServletContext().getRealPath("/") + template.getString(template.Path, ""));
//            oldfile.delete();
//            upfile.renameTo(oldfile);
//            json.put("code", 1);
//            json.put("msg", "操作完成！");
//            json.put("id", id);
//            res.getWriter().write(" " + json.toString());
//        } else {
//            res.sendError(404);
//        }
    }

    private String TimeFile(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(date)
                + upfileFileName.substring(upfileFileName.lastIndexOf("."));
    }

    public void option() throws IOException {
        String option = "<option value=\"%s\">%s</option>";
        Template t = new Template();
        for (Map<String, Object> map : templatedao.find(null, null, null)) {
            res.getWriter()
                    .write(String.format(option, map.get(t.ID),
                            map.get(t.Description)));
        }
    }

    public String execute() {
        //rslist = templatedao.finds(null, pagenumber, pagecount, "template");
        return "SUCCESS";
    }

    public void save() throws IOException {
//        try {
//            if (true){//check.checkUpdateName(updateName) && check.checkId(id)
////                    && check.doCheck(check, updateName, updateValue)) {
//                int rs = 0;
//                //rs = templatedao.update(id, updateName, updateValue);
//
//                JSONObject json = new JSONObject();
//                json.put("code", rs);
//                if (rs == 1) {
//                    json.put("msg", "保存成功！");
//                } else {
//                    json.put("msg", "保存失败！");
//                }
//                res.getWriter().write(json.toString());
//            } else {
//                LOGGER.error("非法参数：id=" + id + ",updateName=" + updateName
//                        + ",updateValue=" + updateValue);
//                res.sendError(404);
//            }
//        } catch (Exception e) {
//            LOGGER.error("异常参数：id=" + id + ",name=" + updateName + ",value="
//                    + updateValue + "：" + e.getMessage());
//            res.sendError(404);
//        }
    }

    public String detail() throws IOException {
        if (true){//check.checkId(id)) {
            template = new Template(templatedao.findById(id));
        } else {
            res.sendError(404);
            return "NONE";
        }

        return "detail";
    }

    public void delete() throws IOException {
        if (!id.equals("")) {
            template = templatedao.removeTemplate(id);
            if (!template.isEmpty()) {
                String tpath = template.getString(template.Path, "");
                //File file = new File(ServletActionContext.getServletContext().getRealPath(tpath));
                File file = new File("");//ServletActionContext.getServletContext().getRealPath(tpath));
                if (file.exists()) {
                    file.delete();
                }
            }
//            JSONObject json = new JSONObject();
//            json.put("code", 1);
//            json.put("msg", "操作完成！");
//            res.getWriter().write(json.toString());

        } else {
            LOGGER.error("非法删除模板文件：id=" + id);
            res.sendError(404);
        }
    }

    public String download() throws IOException {
        if (true){//check.checkId(id)) {
            template = new Template(templatedao.findById(id));
            if (template.isEmpty()) {
                res.sendError(404);
                return "NONE";
            }
            //downloadfile = new File(ServletActionContext.getServletContext().getRealPath(template.getString(template.Path, "")));
            downloadfile = new File("");//ServletActionContext.getServletContext().getRealPath(template.getString(template.Path, "")));
            downloadfilename = downloadfile.getName();
            return "download";
        } else {
            LOGGER.error("非法删除模板文件：id=" + id);
            res.sendError(404);
            return "NONE";
        }
    }

    public Map<String, Object> getRslist() {
        return rslist;
    }

//    public TemplateCheck getCheck() {
//        return check;
//    }

    public Map<String, Object> getTemplate() {
        return template;
    }

    public InputStream getDownloadFile() throws Exception {
        if (downloadfile.exists()) {
            return new FileInputStream(downloadfile);
        } else {
            return null;
        }
    }

    public String getDownloadfilename() {
        return downloadfilename;
    }

}
